﻿using System.Collections.Specialized;
using AutoMapper;
using CNav.Business.Services;
using CNav.Common;
using CNav.Domain;
using CNav.Domain.Admin;
using CNav.Domain.CaseWork;
using CNav.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CNav.Controllers
{
    [Authorize]
    public class EnquiryController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult NewEnquiry()
        {
            var response = Service.Get<IBusinessAccountService>().GetBusiness(LoginUser.BusinessID);
            var enquiryModel = new EnquiryModel();

            var business = response.Data;
            if (business != null)
            {
                var businessModel = Mapper.Map<BusinessModel>(business);

                if (business.AddressID.HasValue)
                {
                    var address = Service.Get<IAddressService>().GetAddress(business.AddressID.Value);
                    businessModel.Address = Mapper.Map<AddressModel>(address.Data);
                }

                enquiryModel.BusinessModel = businessModel;

                var enquiryCustomForm = Service.Get<IConfigurationService>().GetFormConfigurationForStage(Stage.Enquiry);
                var customForm = enquiryCustomForm.Data;

                if (customForm != null)
                {
                    var formId = customForm.FormID.Value;
                    var resFormDetail = Service.Get<IUiService>().GetCustomFormControls(formId);

                    var model = new RenderControlListModel();
                    model.FormID = formId;
                    model.Controls = resFormDetail.Data.Select(Mapper.Map<RenderControlModel>).OrderBy(d => d.DisplayOrder).ToList();

                    enquiryModel.RenderControlListModel = model;
                }

                PopulateUiList();

                return View(enquiryModel);
            }

            return View("NotFound");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult NewEnquiry(EnquiryModel enquiryModel, ConsumerModel consumerModel)
        {
            var response = Service.Get<IBusinessAccountService>().GetBusiness(LoginUser.BusinessID);
            var customFormResponse = Service.Get<IConfigurationService>().GetFormConfigurationForStage(Stage.Enquiry);
            var customForm = customFormResponse.Data;
            List<RenderControl> formSubmitData = null;

            var business = response.Data;
            if (business != null)
            {
                if (customForm != null)
                {
                    formSubmitData = GetCustomFormData(customForm);
                }

                NewEnquiry enquiry =new NewEnquiry();
                enquiry.ProductId = enquiryModel.ProductID ?? 0;
                enquiry.ComplaintType = enquiryModel.ComplaintType ?? 0;
                enquiry.ConsumerId = enquiryModel.ConsumerID ?? 0;
                enquiry.Description = enquiryModel.Description;
                enquiry.BusinessId = business.ID;
                enquiry.UserId = LoginUser.ID;
                enquiry.FormId = customForm != null ? customForm.ID : 0; 

                IEnquiryService enquiryService = Service.Get<IEnquiryService>();
                var addResponse = enquiryService.AddEnquiry(enquiry, formSubmitData);

                if (addResponse.Data == 0)
                {
                    var businessModel = Mapper.Map<BusinessModel>(business);

                    if (business.AddressID.HasValue)
                    {
                        var address = Service.Get<IAddressService>().GetAddress(business.AddressID.Value);
                        businessModel.Address = Mapper.Map<AddressModel>(address.Data);
                    }

                    enquiryModel.BusinessModel = businessModel;

                    if (customForm != null)
                    {
                        var formId = customForm.FormID.Value;
                        var resFormDetail = Service.Get<IUiService>().GetCustomFormControls(formId);

                        var model = new RenderControlListModel();
                        model.FormID = formId;
                        model.Controls = resFormDetail.Data.Select(Mapper.Map<RenderControlModel>).OrderBy(d => d.DisplayOrder).ToList();

                        MergeFormSubmittedData(model, formSubmitData);

                        enquiryModel.RenderControlListModel = model;
                    }

                    PopulateUiList();

                    return View(enquiryModel);
                }

                return RedirectToAction("ViewEnquiry", new {id = addResponse.Data});
            }

            return View("NotFound");
        }

        public ActionResult ViewEnquiry(int id)
        {
         return   RedirectToAction("NewEnquiry");
        }

        private void MergeFormSubmittedData(RenderControlListModel model, List<RenderControl> formSubmitData)
        {
            foreach (var ctToUpdate in model.Controls)
            {
                var submited = formSubmitData.Find(c => c.ID == ctToUpdate.ID);
                if (submited != null)
                    ctToUpdate.Answer = submited.Answer;
            }
        }

        private void PopulateUiList()
        {
            var productResponse = Service.Get<IProductService>().GetProducts();
            ViewBag.ProductList = productResponse.Data.Select(Mapper.Map<ProductModel>);

            var complainResponse = Service.Get<IComplaintService>().GetComplaintTypes();
            ViewBag.ComplaintTypeList = complainResponse.Data.Select(Mapper.Map<ComplaintTypeModel>);
        }

        private List<RenderControl> GetCustomFormData(FormConfiguration formConfig)
        {
            List<RenderControl> list = new List<RenderControl>();
            if (formConfig.FormID.HasValue)
            {
                var resFormDetail = Service.Get<IUiService>().GetCustomFormControls(formConfig.FormID.Value);
                foreach (var item in resFormDetail.Data)
                {
                    var ctrlName = string.Format("{0}_{1}", item.ControlName, item.DisplayOrder);
                    string answer;
                    switch (item.ControlType)
                    {
                        case "CheckBox":
                           answer = GetCheckBoxValue(ctrlName).ToString();
                             break;
                        case "CheckBoxList":
                           answer = GetCheckBoxListValue(ctrlName, item);
                            break;
                        default:
                           answer = GetTextBoxValue(ctrlName);
                             break;
                    }
                    item.Answer = answer;
                    list.Add(item);
                } 
            }
            
            return list;
        }

        private string GetTextBoxValue(string ctrlName)
        {
            return Request[ctrlName] ?? string.Empty;
        }

        private string GetCheckBoxListValue(string ctrlName, RenderControl item)
        {
            List<bool> list = new List<bool>();
            if (item.DataSources != null)
            {
                if (item.DataSources.Any())
                {
                    for (int i = 1; i <= item.DataSources.Count(); i++)
                        list.Add(GetCheckBoxValue(ctrlName + i));
                }
            }

            return  string.Join(",", list);
        }

        private bool GetCheckBoxValue(string name)
        {
            var val = Request[name];
            if (val == null)
                return false;

            return val.StartsWith("true");
        }
    }
}